/**
 * Copyright (c) 1987-2010 Fujian Fujitsu Communication Software Co.,
 * Ltd. All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Fujian Fujitsu Communication Software Co., Ltd.
 * ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with FFCS.
 * FFCS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. FFCS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package aip.ui.dictionary.srvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import aip.core.dao.dictionary.DictionaryDao;
import aip.core.model.dictionary.Dictionary;
import aip.ui.dictionary.utils.DictionaryUtil;
import aip.ui.dictionary.web.spring.DictionaryEditForm;
import aip.ui.dictionary.web.spring.DictionaryListForm;

import com.googlecode.horncomb.bean.paged.PagedList;
import com.googlecode.horncomb.bean.paged.PagedSetting;
import com.googlecode.horncomb.web.spring.context.LocalApplicationContextLocator;
import com.googlecode.horncomb.web.util.TagUtils;

/**
 * Dictionary form service.
 *
 * @author
 * @version Revision 1.0.0
 */
public class DictionaryFormService {
    private DictionaryDao dictionaryDao;
    private static String beanName;

    /**
     * Dictionary列表.
     *
     * @param form
     *            表单对象
     * @return 列表页面数据
     * @throws Exception
     */
    public Map<String, Object> listReference(DictionaryListForm form)
        throws Exception {
        Map<String, Object> ref = new HashMap<String, Object>();
        PagedSetting ps = form.getPagedSettingMap().values().iterator().next();
        PagedList<List<? extends Dictionary>> result = this.dictionaryDao
            .queryAll(ps.getOrder(), ps.getPage(), ps.getPageSize());
        ref.put("dictionaryList", result.getSource()); //$NON-NLS-1$
        ref.put("totalRows", result.getNrOfElements()); //$NON-NLS-1$
        return ref;
    }

    /**
     * 删除选中的项.
     *
     * @param form
     *            表单对象
     * @throws Exception
     */
    public void deleteItems(DictionaryListForm form) throws Exception {
        if (form.getSelectedIds().size() > 0) {
            this.dictionaryDao.deleteByIds(form.getSelectedIds());
        }
    }

    /**
     * 获得Dictionary表单主对象.
     *
     * @param form
     *            表单对象
     * @throws Exception
     */
    public void get(DictionaryEditForm form) throws Exception {
        if (StringUtils.hasText(form.getId())) {
            Dictionary dictionary = this.dictionaryDao.getById(form.getId());
            BeanUtils.copyProperties(dictionary, form);
        }
    }

    /**
     * 显示编辑Dictionary界面相关数据.
     *
     * @param form
     *            表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    public Map<String, Object> showReference(DictionaryEditForm form)
        throws Exception {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        return ref;
    }

    /**
     * 显示编辑通用配置界面相关数据.
     *
     * @param form
     *            表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    public Map<String, Object> showInCommon(DictionaryEditForm form)
        throws Exception {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        form.setDictionaries(this.dictionaryDao.findByShowInCommon(true));
        return ref;
    }

    /**
     * 显示编辑特殊配置界面相关数据.
     *
     * @param form
     *            表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> showSpecial(DictionaryEditForm form)
        throws Exception {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        // 相关连的ID
        String dictRefId = DictionaryUtil.dictRefMap.get(form.getType());
        Set<String> ids = new HashSet<String>();
        ids.add(form.getType());
        ids.add(dictRefId);
        // TODO: 暂时只处理证书 若需要则要修改方法
        List<Dictionary> dictionaries = this.dictionaryDao.findByIds(ids);
        Map<String, Dictionary> dictionarymMap = TagUtils.convertToMap(
            dictionaries, "id");
        //
        ref.put("dictionary", dictionarymMap.get(form.getType()));
        List<Dictionary> dicts = new ArrayList<Dictionary>();
        // 数据是否需要特殊处理，不需要则添加到form的数据字典列表
        Dictionary dictionary = dictionarymMap.get(dictRefId);
        ref.put("refDict", dictionary);
        if (dictionary != null && StringUtils.hasText(dictionary.getValue())) {
            String[] values = StringUtils.delimitedListToStringArray(dictionary
                .getValue(), ";", "\t\r\n\f");
            values = StringUtils.trimArrayElements(values);

            for (String value : values) {
                if (StringUtils.hasText(value)) {
                    String[] labelValue = StringUtils
                        .delimitedListToStringArray(value, "$");
                    labelValue = StringUtils.trimArrayElements(labelValue);
                    Dictionary dict = new Dictionary();
                    dict.setLabel(labelValue[0]);
                    dict.setValue(labelValue.length > 1 ? labelValue[1]
                        : "");
                    dicts.add(dict);
                }
            }
        }
        ref.put("dicts", dicts);
        return ref;
    }

    /**
     * 保存Dictionary表单.
     *
     * @param form
     *            表单对象
     * @throws Exception
     */
    public void save(DictionaryEditForm form) throws Exception {
        // this.dictionaryDao.save(form);
        Assert.notEmpty(form.getDictionaries());
        for (Dictionary dictionary : form.getDictionaries()) {
            if (dictionary != null) {
                this.dictionaryDao.save(dictionary);
            }
        }
    }

    /**
     * 删除单个Dictionary.
     *
     * @param form
     *            表单对象
     * @throws Exception
     */
    public void deleteItem(DictionaryEditForm form) throws Exception {
        this.dictionaryDao.deleteById(form.getId());
    }

    /**
     * 根据参数的键获取参数值字符串
     *
     * @param key
     *            键
     * @return
     * @throws Exception
     */
    public static String loadStrDictionary(String key) throws Exception {
        DictionaryFormService ds = (DictionaryFormService) LocalApplicationContextLocator
            .getLocalApplicationContext().getBean(beanName);

        // 无法获取工具Bean
        if (ds == null) {
            return null;
        }
        return ds.getStrDictionary(key);
    }

    /**
     * 根据参数的键获取参数值字符串
     *
     * @param key
     * @return
     * @throws Exception
     */
    public String getStrDictionary(String key) throws Exception {
        Assert.hasText(key);
        String val = this.dictionaryDao.getStrDictionary(key);
        return val;
    }

    /**
     * 根据参数名与所有者获取参数值，若不存在则取默认参数值
     *
     * @param key
     *            键
     * @return
     * @throws Exception
     */
    public static List<Dictionary> loadDictionary(String key) throws Exception {
        String valStr = loadStrDictionary(key);
        if (valStr == null) {
            return null;
        }

        // 将参数值按";"分割为数组
        List<Dictionary> dicts = new ArrayList<Dictionary>();
        String[] values = StringUtils.delimitedListToStringArray(valStr, ";",
            "\t\r\n\f");
        values = StringUtils.trimArrayElements(values);

        // 若分割后参数是以label/value格式存储的，则继续拆分
        for (String value : values) {
            if (StringUtils.hasText(value)) {
                String[] labelValue = StringUtils.delimitedListToStringArray(
                    value, "/");
                labelValue = StringUtils.trimArrayElements(labelValue);
                Dictionary dict = new Dictionary();
                dict.setLabel(labelValue[0]);
                dict.setValue(labelValue.length > 1 ? labelValue[1]
                    : labelValue[0]);
                dicts.add(dict);
            }
        }
        return dicts;
    }

    /**
     * 根据参数名与所有者获取参数值，若不存在则取默认参数值
     *
     * @param key
     *            键
     * @return
     * @throws Exception
     */
    public static Map<String, String> loadDictMap(String key) throws Exception {
        String valStr = loadStrDictionary(key);
        if (valStr == null) {
            return null;
        }

        // 将参数值按";"分割为数组
        Map<String, String> dictMap = new LinkedHashMap<String, String>();
        String[] values = StringUtils.delimitedListToStringArray(valStr, ";",
            "\t\r\n\f");
        values = StringUtils.trimArrayElements(values);

        // 若分割后参数是以label/value格式存储的，则继续拆分
        for (String value : values) {
            if (StringUtils.hasText(value)) {
                String[] labelValue = StringUtils.delimitedListToStringArray(
                    value, "/");
                labelValue = StringUtils.trimArrayElements(labelValue);
                dictMap.put(labelValue.length > 1 ? labelValue[1]
                    : labelValue[0], labelValue[0]);
            }
        }
        return dictMap;
    }

    /**
     * 根据参数名与所有者获取参数值，若不存在则取默认参数值
     *
     * @param key
     *            键
     * @return
     * @throws Exception
     */
    public static LinkedHashMap<String, ArrayList<String>> loadSpecialDict(
        String key) throws Exception {
        String valStr = loadStrDictionary(key);
        if (valStr == null) {
            return null;
        }
        LinkedHashMap<String, ArrayList<String>> dictMap = new LinkedHashMap<String, ArrayList<String>>();
        // 将参数值按";"分割为数组
        String[] values = StringUtils.delimitedListToStringArray(valStr, ";",
            "\t\r\n\f");
        values = StringUtils.trimArrayElements(values);

        // 若分割后参数是以label/value格式存储的，则继续拆分
        for (String value : values) {
            if (StringUtils.hasText(value)) {
                String[] labelValue = StringUtils.delimitedListToStringArray(
                    value, "$");
                labelValue = StringUtils.trimArrayElements(labelValue);
                ArrayList<String> dictlList = new ArrayList<String>();
                String[] strValues = StringUtils.delimitedListToStringArray(
                    labelValue[1], "*");
                strValues = StringUtils.trimArrayElements(strValues);
                for (String strValue : strValues) {
                    dictlList.add(strValue);
                }
                dictMap.put(labelValue[0], dictlList);
            }
        }
        return dictMap;
    }

    /**
     * @param dictionaryDao
     *            the dictionaryDao to set
     */
    public void setDictionaryDao(DictionaryDao dictionaryDao) {
        this.dictionaryDao = dictionaryDao;
    }

    /**
     * @param beanName
     *            设置beanName属性
     */
    public void setBeanName(String beanName) {
        DictionaryFormService.beanName = beanName;
    }
}
